<template>
    <div class="role-management-container">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="compact-form">
            <el-form-item label="角色名称">
                <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable size="small" />
            </el-form-item>
            <el-form-item label="角色状态">
                <el-select v-model="searchForm.status" placeholder="状态" clearable size="small" style="width: 100px">
                    <el-option label="启用" value="1" />
                    <el-option label="停用" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
                <el-button size="small" @click="handleAdd">新增</el-button>
            </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <vxe-table border show-overflow :data="tableData" height="600" class="compact-table">
            <vxe-column type="seq" title="序号" width="60" align="center" />
            <vxe-column field="name" title="角色名称" />
            <vxe-column field="code" title="权限字符" />
            <vxe-column field="status" title="状态" width="100" align="center">
                <template #default="{ row }">
                    <el-tag :type="row.status === '1' ? 'success' : 'danger'" size="small">
                        {{ row.status === "1" ? "启用" : "停用" }}
                    </el-tag>
                </template>
            </vxe-column>
            <vxe-column field="remark" title="备注" />
            <vxe-column field="createTime" title="创建时间" width="160" />
            <vxe-column field="createUser" title="创建人" width="120" />
            <vxe-column title="操作" width="140" fixed="right" align="center">
                <template #default="{ row }">
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </vxe-column>
        </vxe-table>

        <!-- 编辑抽屉 -->
        <el-drawer v-model="drawerVisible" :title="isEdit ? '编辑角色' : '新增角色'" size="40%" destroy-on-close>
            <div class="compact-drawer">
                <!-- 角色信息表单 -->
                <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px" label-position="top"
                    class="compact-form">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="角色名称" prop="name">
                                <el-input v-model="formData.name" placeholder="请输入角色名称" size="small" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="权限字符" prop="code">
                                <el-input v-model="formData.code" placeholder="请输入权限字符" size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="角色状态" prop="status">
                                <el-select v-model="formData.status" placeholder="请选择状态" size="small"
                                    style="width: 100%">
                                    <el-option label="启用" value="1" />
                                    <el-option label="停用" value="0" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="创建人">
                                <el-input v-model="formData.createUser" placeholder="自动获取" size="small" disabled />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="备注">
                        <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入备注信息"
                            size="small" />
                    </el-form-item>
                </el-form>

                <!-- 权限分配 -->
                <div class="permission-wrapper">
                    <div class="permission-section">
                        <div class="section-header">
                            <h4>菜单权限</h4>
                            <el-button type="primary" link @click="handleSelectAll">全选/全不选</el-button>
                        </div>
                        <el-tree ref="treeRef" :data="menuTree" show-checkbox node-key="id" :props="treeProps"
                            :default-expand-all="true" class="compact-tree" />
                    </div>

                    <div class="permission-section">
                        <div class="section-header">
                            <h4>功能权限</h4>
                        </div>
                        <el-checkbox-group v-model="selectedButtons" class="button-group">
                            <el-checkbox v-for="btn in buttonList" :key="btn.value" :label="btn.value" size="small">{{
                                btn.label
                                }}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </div>

                <div class="drawer-footer">
                    <el-button size="small" @click="drawerVisible = false">取消</el-button>
                    <el-button type="primary" size="small" @click="handleSubmit">保存</el-button>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import type { ElTree, ElForm } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";

interface Role {
    id?: string;
    name: string;
    code: string;
    status: string;
    remark?: string;
    createTime?: string;
    createUser?: string;
    menus?: string[];
    buttons?: string[];
}

interface MenuNode {
    id: string;
    label: string;
    children?: MenuNode[];
}

const searchForm = reactive({
    name: "",
    status: "",
});

const tableData = ref<Role[]>([
    {
        id: "1",
        name: "管理员",
        code: "admin",
        status: "1",
        remark: "系统管理员角色",
        createTime: "2024-03-20 10:00",
        createUser: "system",
        menus: ["1", "11", "12", "13"],
        buttons: ["add", "edit", "delete"],
    },
]);

const drawerVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<InstanceType<typeof ElForm>>();
const treeRef = ref<InstanceType<typeof ElTree>>();

const formData = reactive<Role>({
    name: "",
    code: "",
    status: "1",
    remark: "",
    createUser: "admin",
    menus: [],
    buttons: [],
});

const formRules = reactive({
    name: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    code: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    status: [{ required: true, message: "请选择状态", trigger: "change" }],
});

// 菜单树数据
const menuTree = ref<MenuNode[]>([
    {
        id: "1",
        label: "系统管理",
        children: [
            { id: "11", label: "用户管理" },
            { id: "12", label: "角色管理" },
            { id: "13", label: "菜单管理" },
        ],
    },
    {
        id: "2",
        label: "业务管理",
        children: [
            { id: "21", label: "订单管理" },
            { id: "22", label: "客户管理" },
        ],
    },
]);

const treeProps = {
    children: "children",
    label: "label",
};

const buttonList = [
    { label: "新增", value: "add" },
    { label: "编辑", value: "edit" },
    { label: "删除", value: "delete" },
    { label: "导出", value: "export" },
    { label: "导入", value: "import" },
];

const selectedButtons = ref<string[]>([]);

const handleSearch = () => {
    // 实现搜索逻辑
};

const handleAdd = () => {
    isEdit.value = false;
    Object.assign(formData, {
        name: "",
        code: "",
        status: "1",
        remark: "",
        createUser: "admin",
    });
    selectedButtons.value = [];
    treeRef.value?.setCheckedKeys([]);
    drawerVisible.value = true;
};

const handleEdit = (row: Role) => {
    isEdit.value = true;
    Object.assign(formData, row);
    drawerVisible.value = true;
    nextTick(() => {
        if (row.menus) {
            treeRef.value?.setCheckedKeys(row.menus);
        }
        selectedButtons.value = row.buttons || [];
    });
};

const handleDelete = (row: Role) => {
    ElMessageBox.confirm("确认删除该角色？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        tableData.value = tableData.value.filter((item) => item.id !== row.id);
        ElMessage.success("删除成功");
    });
};

const handleSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            formData.menus = treeRef.value?.getCheckedKeys() as string[];
            formData.buttons = selectedButtons.value;

            if (isEdit.value) {
                // 更新逻辑
                const index = tableData.value.findIndex(
                    (item) => item.id === formData.id
                );
                if (index !== -1) {
                    tableData.value[index] = { ...formData };
                }
            } else {
                // 新增逻辑
                tableData.value.push({
                    ...formData,
                    id: `role_${Date.now()}`,
                    createTime: new Date().toLocaleString(),
                });
            }

            ElMessage.success("保存成功");
            drawerVisible.value = false;
        }
    });
};

const handleSelectAll = () => {
    const keys = treeRef.value?.getCheckedKeys();
    if (keys?.length === menuTree.value.length) {
        treeRef.value?.setCheckedKeys([]);
    } else {
        treeRef.value?.setCheckedKeys(menuTree.value.map((n) => n.id));
    }
};
</script>

<style scoped>
.role-management-container {
    padding: 16px;
    background: #fff;
    border-radius: 4px;
}

.compact-form {
    :deep(.el-form-item) {
        margin-bottom: 12px;
    }
}

.compact-table {
    margin-top: 12px;

    :deep(.vxe-body--row) {
        height: 40px;
    }
}

.compact-drawer {
    padding: 16px;
    height: calc(100vh - 60px);
    display: flex;
    flex-direction: column;

    .permission-wrapper {
        flex: 1;
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        margin-top: 16px;
        overflow: hidden;
    }

    .permission-section {
        height: 100%;
        display: flex;
        flex-direction: column;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        padding: 12px;

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px solid #eee;

            h4 {
                margin: 0;
                font-size: 14px;
                color: #606266;
            }
        }
    }

    .compact-tree {
        flex: 1;
        overflow: auto;
    }

    .button-group {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .drawer-footer {
        margin-top: 16px;
        text-align: right;
        padding-top: 16px;
        border-top: 1px solid #eee;
    }
}
</style>